package com.xwj.controller.front;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xwj.entity.RaRegisterUser;
import com.xwj.service.Impl.RegisterUserServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/front/register/")
public class FrontRegisterController {

    @Autowired
    private RegisterUserServiceImpl registerUserService;

    @RequestMapping(value = "registerData", method = RequestMethod.POST)
    public Map<String, Object> registerData(@RequestParam(value = "mydata") String json) throws ExecutionException, InterruptedException {
        Map<String, Object> map = new HashMap<>();
        RaRegisterUser raRegisterUser = JSON.parseObject(json, new TypeReference<RaRegisterUser>() {
        });
        if (registerUserService.findUserById(raRegisterUser.getId()) != null) {
            map.put("msg", "该账号已存在");
            return map;
        }
        if (registerUserService.findUserByMail(raRegisterUser.getMail()) != null) {
            map.put("msg", "该邮箱已经绑定一个账号，请换一个");
            return map;
        }
        if (registerUserService.findUserByPhone(raRegisterUser.getPhone()) != null) {
            map.put("msg", "该手机号码已经绑定一个账号，请换一个");
            return map;
        }
        raRegisterUser.setCreateTime(new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
        String password;
        if (StringUtils.isBlank(raRegisterUser.getPassword()))
            password = raRegisterUser.getId(); //若没设密码，则默认与账号相同
        else
            password = raRegisterUser.getPassword();
        String slat = UUID.randomUUID().toString().substring(0, 8);
        String spwd = new Md5Hash(password, slat).toString();
        raRegisterUser.setPassword(spwd);
        raRegisterUser.setSalt(slat);
        raRegisterUser.setPhoto("/static/image/photo.jpg");
        map.put("msg", registerUserService.addOneRegisterUserSync(raRegisterUser).get());
        return map;
    }

}
